<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form
            size="small"
            ref="searchFormRef"
            :model="searchForm"
            layout="inline"
            label-align="right"
          >
            <a-form-item label="公司" field="firm">
              <a-cascader
                v-model="searchForm.firmId"
                :options="firmOptions"
                allow-clear
                class="bacClass"
                :style="{ width: '220px' }"
                popup-container="html"
              />
            </a-form-item>
            <a-form-item label="入库单号">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="searchForm.rukudanhao"
                @press-enter="doRefresh"
              />
            </a-form-item>
            <a-form-item label="日期">
              <a-date-picker
                popup-container="html"
                v-model="searchForm.beginDate"
                :style="{ width: '230px' }"
                class="bacClass"
              />
            </a-form-item>
            <a-form-item label="至">
              <a-date-picker
                popup-container="html"
                v-model="searchForm.endDate"
                :style="{ width: '240px' }"
                class="bacClass"
              />
            </a-form-item>
            <a-form-item label="审核状态">
              <a-select
                popup-container="html"
                allow-clear
                class="bacClass"
                v-model="searchForm.auditState"
                @press-enter="doRefresh"
              >
                <a-option :value="2">全部</a-option>
                <a-option :value="0">未审核</a-option>
                <a-option :value="1">已审核</a-option>
              </a-select>
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <el-button type="primary" :icon="Search" @click="selectHandler" v-hasPermi="['cpcrk.cx']">查询</el-button>
        <el-button type="success" :icon="CirclePlus" @click="addInstock" v-hasPermi="['cpcrk.xzrk']">新增入库</el-button>
        <el-button :icon="Coordinate" @click="auditHandler" v-hasPermi="['cpcrk.sh']">审核</el-button>
        <el-button :icon="EditPen" @click="disAduitHandler" v-hasPermi="['cpcrk.fs']">反审</el-button>
        <el-button :icon="Delete" @click="deleteHandler" v-hasPermi="['cpcrk.sc']">删除</el-button>
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="onLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid
            ref="table1Ref"
            :configaggrid="configaggrid"
            @change:rowSelected="handleRowSelected"
          ></encapsulation-agrid>
        </div>
      </a-spin>
    </template>

    <!-- 点击修改按钮弹出的抽屉、新增入库的抽屉 -->
    <EditDrawer
      v-model:visible="editDrawerVisible"
      :title="editDrawerTitle"
      position="bottom"
      :data="transferData"
      @update:visible="handleDrawerClose"
      @getList="doRefresh"
    />
    <!-- 弹窗提示 -->
    <a-modal
      v-model:visible="tipModalConfig.visible"
      width="350px"
      @ok="tipModalOk"
      @cancel="tipModalConfig.visible = false"
    >
      <template #title>
        <span style="font-size: 16px; font-weight: 600; color: #000000">提示</span>
      </template>
      <div>确认要{{ tipModalConfig.contorlType }}当前数据吗?</div>
    </a-modal>
  </pageTabelLayout>
</template>

<script setup lang="ts">
  import { ref, reactive,onBeforeUnmount, onMounted} from 'vue'
  import usePermission from '@/store/modules/permission'
  import { tableColumns } from './tableConfig/index.ts'
  import { post } from '@/api/http'
  import { Message } from '@arco-design/web-vue'
  import { Search, CirclePlus, Edit, Coordinate, EditPen, Delete } from '@element-plus/icons-vue'
  import EditDrawer from './components/EditDrawer.vue'
  import emitter from '@/hooks/useEventBus.ts'
  const permissionStore = usePermission()
  onMounted(() => {
    emitter.on('FinishedProductInstock-edit',(data:any)=>editHandler(data))
    getFirmOptions()
  })
  onBeforeUnmount(()=>{
    emitter.off('FinishedProductInstock-edit',(data:any)=>editHandler(data))
  })
  const headerShow = ref<boolean>(true)
  const onLoading = ref<boolean>(false)
  const searchForm = reactive<any>({
    firmId: '',
    beginDate: '',
    endDate: '',
    auditState: 0,
  })
  const searchFormRef = ref<any>(null)
  const firmOptions = ref<any>([])
  const editDrawerTitle = ref<string>('')
  //传递给抽屉的数据
  const transferData = reactive<any>({
    firmOptions: [],
    tableData: [],
    searchData: {},
  })
  // 获取公司下拉框
  const getFirmOptions = () => {
    post({
      url: 'org/baCompany/getTreeCompanyByUser',
      data: {},
    }).then((result: any) => {
      if (result.code === 200) {
        firmOptions.value = result.data
        transferData.firmOptions = result.data
      } else {
        Message.error(result.message)
      }
    })
  }
  let configaggrid = ref({
    url: '/wms/ProductStockIn/getPage', //接口路径
    queryData: {
      //接口参数
      companyId: searchForm.firmId,
      stockInCode: searchForm.rukudanhao,
      beginDate: searchForm.beginDate,
      endDate: searchForm.endDate,
      auditState: searchForm.auditState==2?null:searchForm.auditState,
    },
    paginationShow: true, //分页是否显示
    invokeiIterface: true, //是否调用接
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns,
  })
  const table1Ref = ref<any>(null)
  //勾选/取消勾选相同入库单号的行数据操作
  const handleRowSelected = (event: any) => {
    const { data, selected } = event.node
    table1Ref.value.forEachNode((node: any) => {
      const { stockInCode } = node.data
      if (data.stockInCode == stockInCode) node.setSelected(selected)
    })
  }
  const doRefresh = async () => {
    try {
      if (onLoading.value) return
      onLoading.value = true
      await table1Ref.value.setQuery({
        companyId: searchForm.firmId,
        stockInCode: searchForm.rukudanhao,
        beginDate: searchForm.beginDate,
        endDate: searchForm.endDate,
        auditState: searchForm.auditState==2?null:searchForm.auditState,
      })
    } catch (e) {
      console.log(e)
    } finally {
      onLoading.value = false
    }
  }
  const selectHandler = () => {
    doRefresh()
  }
  const editDrawerVisible = ref<boolean>(false)
  //新增入库按钮
  const addInstock = () => {
    editDrawerTitle.value = '新增入库'
    editDrawerVisible.value = true
  }
  //修改按钮
  const editHandler = async (data:any) => {
    try {
      const res = await post({
        url: '/wms/ProductStockInDetail/getList',
        data: {
          stockInId: data.id,
        },
      })
      if (res.code == 200) {
        transferData.searchData = data //传过去子组件 用于回显表单数据
        transferData.tableData = res.data
        editDrawerTitle.value = '修改'
        editDrawerVisible.value = true
      } else {
        Message.error(res.message)
      }
    } catch (e) {
      console.log(e)
    }
  }
  const handleDrawerClose=(visible:boolean)=>{
    editDrawerVisible.value=visible
    transferData.searchData={} //清空表单数据
    transferData.tableData=[]
  }
  const tipModalConfig = reactive({
    contorlType: '',
    visible: false,
  })
  const tipModalOk = async () => {
    try {
      if (tipModalConfig.contorlType == '审核') {
        const data = JSON.parse(JSON.stringify(table1Ref.value.getSelectedRows()))
        const uniqueObj=data.reduce((acc:any,cur:any)=>{
          acc[cur.id]={
            id:cur.id,
            auditState:1
          }
          return acc
        },{})
        const uniqueArr=Object.values(uniqueObj)
        const res = await post({
          url: '/wms/ProductStockIn/setAudit',
          data:uniqueArr,
        })
        if (res.code == 200) {
          tipModalConfig.visible = false
          Message.success(res.message)
          doRefresh()
        } else {
          Message.error(res.message)
        }
      } else if (tipModalConfig.contorlType == '删除') {
        const res = await post({
          url: '/wms/ProductStockIn/delete',
          data: [...new Set(table1Ref.value.getSelectedRows().map((item: any) => item.id))],
        })
        if (res.code == 200) {
          tipModalConfig.visible = false
          Message.success(res.message)
          doRefresh()
        } else {
          Message.error(res.message)
        }
      } else if (tipModalConfig.contorlType == '反审') {
        const data = JSON.parse(JSON.stringify(table1Ref.value.getSelectedRows()))
        const uniqueObj=data.reduce((acc:any,cur:any)=>{
          acc[cur.id]={
            id:cur.id,
            auditState:0
          }
          return acc
        },{})
        const uniqueArr=Object.values(uniqueObj)
        const res = await post({
          url: '/wms/ProductStockIn/setBackAudit',
          data:uniqueArr,
        })
        if (res.code == 200) {
          tipModalConfig.visible = false
          Message.success(res.message)
          doRefresh()
        } else {
          Message.error(res.message)
        }
      }
    } catch (e) {
      console.log(e)
    }
  }
  //审核按钮
  const auditHandler = () => {
    if (table1Ref.value.getSelectedRows().length == 0) {
      Message.error('请选择一条或多条数据进行审核')
      return
    }
    if (table1Ref.value.getSelectedRows().some((item: any) => item.auditState == 1)) {
      Message.error('已审核的数据不能进行审核')
      return
    }
    tipModalConfig.contorlType = '审核'
    tipModalConfig.visible = true
  }
  //反审按钮
  const disAduitHandler = () => {
    if (table1Ref.value.getSelectedRows().length == 0) {
      Message.error('请选择一条或多条数据进行反审')
      return
    }
    if(table1Ref.value.getSelectedRows().some((item:any)=>item.auditState==0)) {
      Message.error('未审核的数据不能进行反审')
      return
    }
    tipModalConfig.contorlType = '反审'
    tipModalConfig.visible = true
  }
  //删除按钮
  const deleteHandler = () => {
    if (table1Ref.value.getSelectedRows().length == 0) {
      Message.error('请选择一条或多条数据进行删除')
      return
    }
    tipModalConfig.contorlType = '删除'
    tipModalConfig.visible = true
  }
</script>
<style scoped>
  #Table td,
  #Table th {
    border: 1px solid #ccc;
    padding: 10px;
  }

  .tdStyle {
    min-width: 100px;
  }

  .notClick {
    background-color: gray;
    cursor: no-drop;
  }

  :deep(.SendCheck) {
    z-index: 100 !important;
  }

  :deep(.arco-table-th) {
    border-right: 1px solid var(--color-neutral-3);
  }

  :deep(.arco-table-td) {
    border-right: 1px solid var(--color-neutral-3);
  }
  .my-tool-bar {
    padding: 5px;
  }
</style>
